import {
  UPDATE_KEYS,
  FETCH_KEYS,
  CHECK_KEY,
  UNCHECK_KEY,
  UPDATE_KEY_METADATA
} from '../actions/s3key';

export default function s3key(
  state = { isFetchingKeys: false, s3keys: [], prefix: '', checkedS3keys: [], metadata: {} },
  action
) {
  switch (action.type) {
    case FETCH_KEYS:
      return {
        ...state,
        isFetchingKeys: true
      };

    case UPDATE_KEYS:
      return {
        ...state,
        isFetchingKeys: false,
        s3keys: [...action.payload.s3keys],
        prefix: action.payload.prefix,
        checkedS3keys: []
      };
    case CHECK_KEY:
      const newCheckedKey = [...state.checkedS3keys, ...action.payload.keys];
      return {
        ...state,
        checkedS3keys: newCheckedKey
      };
    case UNCHECK_KEY:
      let newCheckedKey1 = [...state.checkedS3keys];
      
      action.payload.keys.forEach(k=>newCheckedKey1.splice(newCheckedKey1.indexOf(k), 1));
      
      return {
        ...state,
        checkedS3keys: newCheckedKey1
      };
    case UPDATE_KEY_METADATA:
      return {
        ...state,
        metadata: action.payload.metadata
      }
    default:
      return state;
  }
}
